/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.base.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.URLUtil;
import com.iwindplus.base.domain.constant.CommonConstant;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

/**
 * url处理工具类.
 *
 * @author zengdegui
 * @since 2021/1/11
 */
@Slf4j
public class UrlUtil extends URLUtil {

    private static final ConcurrentHashMap<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>(16);

    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    private UrlUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * 检验是否匹配（支持通配符，前缀相同就通过）.
     *
     * @param urlList url集合
     * @param reqUrl  请求地址
     * @return boolean
     */
    public static boolean isMatchLike(List<String> urlList, String reqUrl) {
        if (CollUtil.isEmpty(urlList)) {
            return false;
        }

        for (String raw : urlList) {
            Pattern pattern = PATTERN_CACHE.computeIfAbsent(raw, k -> {
                String regex = k.replaceAll("\\*\\*", "(.*?)");
                return Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
            });
            if (pattern.matcher(reqUrl).find()) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检验是否匹配（全匹配）.
     *
     * @param urlList url集合
     * @param reqUrl  请求地址
     * @return boolean
     */
    public static boolean isMatch(List<String> urlList, String reqUrl) {
        if (CollUtil.isEmpty(urlList)) {
            return false;
        }
        for (String url : urlList) {
            boolean match = MATCHER.match(url, reqUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
